package array;

public class BinarySearch {
	public static int bs(int[] array, int x) {
		if (array == null)
			return -1;
		int start = 0;
		int end = array.length - 1;
		while (start <= end) {
			int m = start + ((end - start) >> 1);
			if (array[m] == x)
				return m;
			else if (array[m] < x)
				start = m + 1;
			else
				end = m - 1;
		}
		return -1;
	}
	
	public static int bsNear(int[] array, int x, int endP) {
		if (array == null)
			return -1;
		int start = 0;
		int end = endP;
		while (start <= end) {
			if(start == end)
				return start;
			int m = start + ((end - start) >> 1);
			if (array[m] == x)
				return m;
			else if (array[m] < x)
				start = m + 1;
			else
				end = m;
		}
		return -1;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] array = {1, 3, 4, 8, 16, 20, 30, 41, 17};
		System.out.println(bs(array, 16));
	}

}
